package com.atguigu.cloud.mygateway;

import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.AfterRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * @Author: huahua
 * @Date: 2024/6/11 0011
 * @Time: 15:11
 * @Description: 自定义Gateway断言
 * 需求说明：自定义配置会员等级userType,按照钻/金/银和yml配置的会员等级，以适配是否可以访问
 * 问题：正常按照源码实现的缺少shortcutFieldOrder方法的实现，所以不支持短格式
 *      全面配置：
 *      - name: My
 *        args:
 *           userType: diamond
 * 解决：实现  shortcutFieldOrder 实现短促格式
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {

    @Validated
    public static class Config {

        @Setter @Getter @NotEmpty
        private String userType; //会员等级
    }

    public MyRoutePredicateFactory() {
        super(MyRoutePredicateFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userType");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                //检查request的参数里面，userType是否为指定的值，符合配置就通过
                //http:xxx/xxx?userType = diamond
                String userType = serverWebExchange.getRequest().getQueryParams().getFirst("userType");

                if(userType == null){
                    return false;

                }else if(userType.equalsIgnoreCase(config.getUserType())){//如果说参数存在，就和config的数据进行比较
                    return true;
                }
                return false;
            }
        };
    }


}
